package com.jinbiao.quasar.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.jinbiao.quasar.annotate.OperationLog;
import com.jinbiao.quasar.model.SysLogOperation;
import com.jinbiao.quasar.util.AjaxJson;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.extend.sqltoy.annotation.Db;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;
import org.sagacity.sqltoy.model.Page;

import java.util.List;

@Controller
@OperationLog
public class LogOperationController {
    @Db
    SqlToyLazyDao dao;
    @Mapping("/log/get-log-operation-list")
    public AjaxJson getLogOperationList(int page,int pageSize,String sortBy,boolean desc,SysLogOperation sysLogOperation){
        String sqlTemplate = "SELECT * FROM sys_log_operation WHERE" +
                "            #[and operation_username=:operationUsername]" +
                "            #[and operation_ip like :operationIp]" +
                "            #[and operation_method=:operationMethod]" +
                "            #[and operation_api like :operationApi]" +
                "            #[and operation_status=:operationStatus]" +
                "            #[and operation_body like :operationBody]" +
                " order by {} {}";
        String sql = StrUtil.format(sqlTemplate, sortBy, desc ? "desc" : "asc");
        Page<SysLogOperation> pageResult =  dao.findPageBySql(new Page(pageSize, page), sql, BeanUtil.beanToMap(sysLogOperation),SysLogOperation.class);
        return AjaxJson.getSuccessData(pageResult);
    }

    @Mapping("/log/delete-log-operation-by-id")
    public AjaxJson deleteLogOperationById(SysLogOperation sysLogOperation){
        return AjaxJson.getSuccessData(dao.delete(sysLogOperation));
    }

    @Mapping("/log/edit-log")
    public AjaxJson editLogOperation(SysLogOperation sysLogOperation){
        return AjaxJson.getSuccessData(dao.saveOrUpdate(sysLogOperation));
    }

    @Mapping("/log/add-log")
    public AjaxJson addLogOperation(SysLogOperation sysLogOperation){
        return AjaxJson.getSuccessData(dao.saveOrUpdate(sysLogOperation));
    }

    @Mapping("/log/query-log-operation-by-id")
    public AjaxJson queryLogOperationById(SysLogOperation sysLogOperation){
        List<SysLogOperation> results = dao.findBySql("sysLogOperationList",sysLogOperation);
        if(CollectionUtil.isNotEmpty(results)){
            SysLogOperation configBackend = results.get(0);
            return AjaxJson.getSuccessData(configBackend);
        }
        return AjaxJson.getSuccessData(null);
    }

    @Mapping("/public/get-log-operation-all")
    public AjaxJson getLogOperationAll(SysLogOperation sysLogOperation){
        return AjaxJson.getSuccessData(dao.findBySql("sysLogOperationList",sysLogOperation));
    }
}
